<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
    <meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0">
    <title>购物车 - 钢域云贸</title>
    <link rel="icon" href="/uploads/logo.png" type="image/x-icon"/>
    <link rel="shortcut icon" href="/uploads/logo.png" type="image/x-icon"/>
    <link rel="stylesheet" type="text/css" href="/css/public.css"/>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        /* 表单样式优化 */
        .form-label {
            font-weight: 500;
            color: #4b5563;
        }
        .form-input {
            transition: all 0.2s ease-in-out;
        }
        .form-input:focus {
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        }
        /* 主内容区域样式 */
        main {
            display: flex;
            min-height: calc(100vh - 64px - 64px); /* 减去 header 和 footer 高度（假设各 64px） */
            width: 100%;
        }
        /* 侧边栏样式 */
        .sidebar {
            width: 256px; /* 保持当前宽度 */
            background-color: #fff;
            box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
            display: flex;
            flex-direction: column;
        }
        /* 内容区域样式 */
        .content-area {
            flex: 1;
            padding: 2rem;
            background-color: #f7fafc; /* 匹配背景色 */
        }
        /* 确保侧边栏内容区自适应 */
        .sidebar nav {
            flex-grow: 1;
        }
        /* 响应式布局 */
        @media (max-width: 640px) {
            .sidebar {
                display: none;
            }
            .content-area {
                padding: 1rem;
            }
        }
        .bg-blue-600 {
            --tw-bg-opacity: 1;
            background-color: rgb(86 102 192);
        }
        .bg-red-600 {
            --tw-bg-opacity: 1;
            background-color: rgb(255, 99, 99);
        }
    </style>
</head>

<body class="bg-gray-100 min-h-screen">
<!-- 公共头部 -->
<th:block th:replace="~{/header.html}"></th:block>
<!-- Main Content -->
<main>
    <!-- 侧边栏 -->
    <th:block th:replace="~{/buyer/sidebar.html}"></th:block>
    <!-- 内容区域 -->
    <div class="content-area">
        <!-- 权限检查 -->
        <div th:if="${session.user == null or session.user.role != 'BUYER'}" class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4 text-center">
            <span>请以买家身份登录后访问购物车！</span>
            <a th:href="@{/login(url='/buyer/cart/view')}" class="text-blue-600 hover:underline ml-2">立即登录</a>
        </div>

        <!-- 仅在用户登录且角色为 BUYER 时显示购物车内容 -->
        <div th:if="${session.user != null and session.user.role == 'BUYER'}">
            <!-- 错误提示 -->
            <div th:if="${errorMessage}" class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4" role="alert">
                <span th:text="${errorMessage}"></span>
            </div>

            <div id="cart_list" class="bg-white p-8 rounded-xl shadow-lg">
                <form id="cart_form" th:action="@{/buyer/cart/update}" method="post">
                    <input type="hidden" name="${_csrf.parameterName}" th:value="${_csrf.token}"/>
                    <table class="w-full">
                        <thead>
                        <tr class="border-b">
                            <th class="p-3 text-left text-gray-700">
                                <input type="checkbox" id="select-all" checked="checked" onchange="toggleSelectAll(this)">
                                <label for="select-all" class="ml-2">全选</label>
                            </th>
                            <th class="p-3 text-left text-gray-700">商品</th>
                            <th class="p-3 text-left text-gray-700">价格</th>
                            <th class="p-3 text-left text-gray-700">数量</th>
                            <th class="p-3 text-left text-gray-700">小计</th>
                        </tr>
                        </thead>
                        <tbody id="cart_table_body">
                        <tr th:each="item : ${carts}" class="border-b hover:bg-gray-50" th:data-id="${item.id}" th:data-product-id="${item.productId}">
                            <td class="p-3">
                                <input type="checkbox" class="cart-item-checkbox" th:checked="${item.selected}" th:name="'selected_' + ${item.id}" th:value="true" onchange="updateCheckbox(this)">
                                <input type="hidden" th:name="'selected_' + ${item.id}" value="false"/>
                            </td>
                            <td class="p-3 flex items-center">
                                <img th:src="${item.productImage} ?: '/Uploads/img.png'" th:alt="${item.productName}" class="w-16 h-16 object-cover rounded-lg">
                                <span class="ml-4 text-gray-800" th:text="${item.productName}"></span>
                            </td>
                            <td class="p-3 text-gray-800" th:text="'¥' + ${#numbers.formatDecimal(item.price, 1, 2)}"></td>
                            <td class="p-3">
                                <div class="flex items-center space-x-2">
                                    <input type="number" min="1" th:name="'quantity_' + ${item.id}" th:value="${item.quantity}" class="quantity-input border p-1 rounded w-16 text-center" data-cart-id="${item.id}" data-product-id="${item.productId}" onchange="debounceUpdateQuantity(this)">
                                </div>
                            </td>
                            <td class="p-3 text-gray-800 subtotal" th:text="'¥' + ${#numbers.formatDecimal(item.price * item.quantity, 1, 2)}"></td>
                        </tr>
                        <tr th:unless="${carts}">
                            <td colspan="6" class="p-3 text-center text-gray-500">购物车为空</td>
                        </tr>
                        </tbody>
                    </table>
                    <div class="mt-4">
                        <button type="submit" class="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700">更新购物车</button>
                    </div>
                </form>
            </div>
            <!-- Cart Footer -->
            <div class="flex justify-between items-center mt-8">
                <span id="total_price" class="text-2xl font-semibold text-gray-800"></span>
                <div class="flex flex-wrap gap-4 mt-6">
                    <form id="delete-selected-form" th:action="@{/buyer/cart/delete-selected}" method="post" class="flex items-center">
                        <input type="hidden" name="${_csrf.parameterName}" th:value="${_csrf.token}"/>
                        <th:block th:each="item : ${carts}">
                            <input type="hidden" class="delete-selected-hidden" th:data-id="${item.id}" th:name="'selected_' + ${item.id}" th:value="${item.selected ? 'true' : 'false'}"/>
                        </th:block>
                        <button type="submit" onclick="return confirm('确认删除选中的商品？')" class="flex items-center px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 transition">
                            <i class="fas fa-trash mr-2"></i> 删除选中
                        </button>
                    </form>

                    <form th:action="@{/buyer/cart/clear}" method="post" class="flex items-center">
                        <input type="hidden" name="${_csrf.parameterName}" th:value="${_csrf.token}"/>
                        <button type="submit" onclick="return confirm('确认清空购物车？')" class="flex items-center px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 transition">
                            <i class="fas fa-trash-alt mr-2"></i> 清空购物车
                        </button>
                    </form>



<!--                    <a th:href="@{/buyer/checkout}" class="flex items-center px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition">-->
<!--                        <i class="fas fa-credit-card mr-2"></i> 去结算-->
<!--                    </a>-->
                    <form th:action="@{/buyer/checkout/multi}" method="post" id="checkoutForm">
                        <input type="hidden" name="${_csrf.parameterName}" th:value="${_csrf.token}"/>

                        <!-- 传递选中的商品 -->
                        <th:block th:each="item : ${carts}" th:if="${item.selected}">
                            <input type="hidden" name="productIds" th:value="${item.productId}"/>
                            <input type="hidden" name="quantities" th:value="${item.quantity}"/>
                        </th:block>

                        <button type="submit" class="flex items-center px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition"
                                th:disabled="${#lists.size(carts.?[selected == true]) == 0}">
                            <i class="fas fa-credit-card mr-2"></i> 去结算
                        </button>
                    </form>

                </div>

            </div>
        </div>
    </div>
</main>
<!-- 公共底部 -->
<th:block th:replace="~{/footer.html}"></th:block>

<script src="/js/jquery-latest.min.js"></script>
<script src="/js/popper.min.js"></script>
<script src="/js/bootstrap.min.js"></script>
<script>
    // 初始化
    document.addEventListener('DOMContentLoaded', () => {
        updateTotalPrice();
        updateSelectAllCheckbox();
        const success = /*[[${success}]]*/ false;
        const error = /*[[${error}]]*/ null;
        if (success) {
            showToast('✅ 操作成功！');
        } else if (error) {
            showToast('❌ ' + error);
        }
    });

    // 防抖函数
    function debounce(func, wait) {
        let timeout;
        return function (...args) {
            clearTimeout(timeout);
            timeout = setTimeout(() => func.apply(this, args), wait);
        };
    }

    // 全选/取消全选
    function toggleSelectAll(checkbox) {
        const form = document.getElementById('cart_form');
        document.querySelectorAll('.cart-item-checkbox').forEach(cb => {
            cb.checked = checkbox.checked;
            cb.value = checkbox.checked ? 'true' : 'false';
            // 更新隐藏输入框
            const hiddenInput = cb.nextElementSibling;
            if (hiddenInput) {
                hiddenInput.value = checkbox.checked ? 'true' : 'false';
            }
            // 更新 delete-selected-form 中的隐藏输入框
            const deleteHiddenInput = document.querySelector(`.delete-selected-hidden[data-id="${cb.closest('tr').dataset.id}"]`);
            if (deleteHiddenInput) {
                deleteHiddenInput.value = checkbox.checked ? 'true' : 'false';
            }
        });
        updateTotalPrice();
        updateSelectAllCheckbox();
        form.submit(); // 提交表单以更新服务器端状态
    }

    // 更新复选框状态
    function updateCheckbox(checkbox) {
        checkbox.value = checkbox.checked ? 'true' : 'false';
        // 更新隐藏输入框
        const hiddenInput = checkbox.nextElementSibling;
        if (hiddenInput) {
            hiddenInput.value = checkbox.checked ? 'true' : 'false';
        }
        // 更新 delete-selected-form 中的隐藏输入框
        const deleteHiddenInput = document.querySelector(`.delete-selected-hidden[data-id="${checkbox.closest('tr').dataset.id}"]`);
        if (deleteHiddenInput) {
            deleteHiddenInput.value = checkbox.checked ? 'true' : 'false';
        }
        updateTotalPrice();
        updateSelectAllCheckbox();
        // 不立即提交表单，等待用户点击“更新购物车”按钮
    }

    // 更新数量（带防抖）
    const debounceUpdateQuantity = debounce(function (input) {
        updateSubtotal(input);
        // 不立即提交表单，等待用户点击“更新购物车”按钮
    }, 500);

    // 更新全选复选框状态
    function updateSelectAllCheckbox() {
        const checkboxes = document.querySelectorAll('.cart-item-checkbox');
        const selectAllCheckbox = document.getElementById('select-all');
        const allChecked = Array.from(checkboxes).every(cb => cb.checked);
        const someChecked = Array.from(checkboxes).some(cb => cb.checked);

        selectAllCheckbox.checked = allChecked;
        selectAllCheckbox.indeterminate = !allChecked && someChecked;
    }

    // 计算选中商品总价
    function updateTotalPrice() {
        const rows = document.querySelectorAll('#cart_table_body tr[data-id]');
        let totalPrice = 0;

        rows.forEach(row => {
            const checkbox = row.querySelector('.cart-item-checkbox');
            if (checkbox.checked) {
                const priceText = row.querySelector('td:nth-child(3)').textContent.replace('¥', '').trim();
                const quantity = parseInt(row.querySelector('.quantity-input').value);
                const price = parseFloat(priceText);
                if (!isNaN(price) && !isNaN(quantity)) {
                    totalPrice += price * quantity;
                }
            }
        });

        document.getElementById('total_price').textContent = `总计：¥${totalPrice.toFixed(2)}`;
    }

    // 更新小计
    function updateSubtotal(input) {
        const row = input.closest('tr');
        const priceText = row.querySelector('td:nth-child(3)').textContent.replace('¥', '').trim();
        const quantity = parseInt(input.value);
        const price = parseFloat(priceText);
        if (!isNaN(price) && !isNaN(quantity) && quantity > 0) {
            const subtotal = price * quantity;
            row.querySelector('.subtotal').textContent = `¥${subtotal.toFixed(2)}`;
        } else {
            input.value = 1; // 防止无效输入
        }
        updateTotalPrice();
    }

    // 显示提示
    function showToast(message) {
        const toast = document.createElement('div');
        toast.className = 'fixed top-4 right-4 bg-gray-800 text-white px-4 py-2 rounded shadow-lg';
        toast.textContent = message;
        document.body.appendChild(toast);
        setTimeout(() => toast.remove(), 3000);
    }
</script>
</body>
</html>